package com.xiexie.seckill.rabbitMQ;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * rabbitMQ 发送消息
 */
@Service
@Slf4j
public class RabbitMQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sent(Object msg) {
        log.info("发送消息：" + msg);
        rabbitTemplate.convertAndSend("queue", msg);
    }

    /**
     * 将消息直接发送到交换机上  fanout广播模式 不需要路由键
     * @param msg
     */
    public void sentFanoutExcahnge(Object msg) {
        // 发送不需要路由键
        rabbitTemplate.convertAndSend("fanoutExchange", "",msg);
    }

    /**
     * 据路由键来判断交换机的哪一个队列来做处理
     * @param msg
     */
    public void sentDirectExchange(Object msg) {
        rabbitTemplate.convertAndSend("directExchange", "direct.queue.red", msg);
    }

    public void sentDirectExchange2(Object msg) {
        rabbitTemplate.convertAndSend("directExchange", "direct.queue.green", msg);
    }

    /**
     * topic 匹配模式 （匹配#通配符）
     * @param msg
     */
    public void sentTopicExchange1(Object msg) {
        // 只能被一个接收
        rabbitTemplate.convertAndSend("topicExchange", "queue.red.message", msg);
    }

    /**
     * topic 匹配模式 （只匹配*通配符）
     * @param msg
     */
    public void sentTopicExchange2(Object msg) {
        // 能被两个接收
        rabbitTemplate.convertAndSend("topicExchange", "topic.queue.green.message", msg);
    }


    /**
     * headers模式 匹配header信息
     * @param msg
     */
    public void sentHeadersExchange1(String msg) {
        // 能被两个接收
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("color", "red");
        messageProperties.setHeader("speed", "fast");
        Message message = new Message(msg.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend("headersExchange", "", message);
    }

    public void sentHeadersExchange2(String msg) {
        // 能被一个接收
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("color", "red");
        messageProperties.setHeader("speed", "normal");
        Message message = new Message(msg.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend("headersExchange", "", message);
    }


    /**
     * 发送业务代码  秒杀信息
     * @param message
     */
    public void sendSeckillMessage(String message) {
        rabbitTemplate.convertAndSend("seckillExchange", "seckill.message", message);
    }


}
